package route

import (
	"github.com/fsnotify/fsnotify"
	"github.com/kataras/iris/v12"
	"knife4g-server/conf"
	"knife4g-server/knife4g"
	"knife4g-server/utils"
	"log"
	"strings"
)

var watcher *fsnotify.Watcher

func InitRouter(app *iris.Application) {
	if conf.Config.Hot {
		go func() {
			var err error
			watcher, err = fsnotify.NewWatcher()
			if err != nil {
				log.Fatal(err)
			}
			defer func(watcher *fsnotify.Watcher) {
				_ = watcher.Close()
			}(watcher)
			done := make(chan bool)
			go func() {
				defer func() {
					if err := recover(); err != nil {
						log.Println(err)
					}
				}()
				for {
					select {
					case event := <-watcher.Events:
						if event.Op&(fsnotify.Write|fsnotify.Create) != 0 {
							path := event.Name
							docPath := strings.TrimPrefix(path, conf.Dir)
							docData := utils.JsonDecodeFile(path)
							if docData != nil {
								knife4g.DocDataMap[docPath] = docData
							}
						}
					case err := <-watcher.Errors:
						log.Println("Error:", err)
					}
				}
			}()
			<-done
		}()
	}
	LoadRouter(app)
}

func LoadRouter(app *iris.Application) {
	for _, namespace := range conf.Config.Namespaces {
		app.Get("/"+namespace.Name+"/{any:path}", knife4g.Handler(knife4g.Config{RelativePath: "/" + namespace.Name, Namespace: namespace}))
		if conf.Config.Hot {
			for _, doc := range namespace.Docs {
				_ = watcher.Add(doc.DocPath)
			}
		}
	}
}
